package com.jvtd.eyl.ui.main.bookcase;


import android.text.TextUtils;

import com.jvtd.bean.EmptyBean;
import com.jvtd.eyl.base.BasePresenter;
import com.jvtd.eyl.bean.http.MyBookBean;
import com.jvtd.eyl.data.DbManager;
import com.jvtd.eyl.rxjava.JvtdRxSchedulers;
import com.jvtd.rxjava.JvtdObserverSubscriber;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;

/**
 * 书架
 *
 * 作者:chenlei
 * 时间:2018/11/15 1:11 PM
 */
public class BookcasePresenter<V extends BookcaseMvpView> extends BasePresenter<V> implements BookcaseMvpPresenter<V>
{
  @Inject
  public BookcasePresenter(DbManager dbManager, CompositeDisposable disposable)
  {
    super(dbManager, disposable);
  }

  @Override
  public void onAttach(V mvpView)
  {
    super.onAttach(mvpView);
  }

  @Override
  public void getMyBookList() {
    if (!isAttachView()) return;
    getCompositeDisposable().add(getDbManager().getMyBookList(getCurrentUser().getUserId())
    .compose(JvtdRxSchedulers.handleObservableResult())
    .subscribeWith(new JvtdObserverSubscriber<List<MyBookBean>>(getMvpView()){
      @Override
      public void onNext(List<MyBookBean> bookBeans) {
        super.onNext(bookBeans);
        if (isAttachView()) {
          for (MyBookBean bookBean : bookBeans) {
            bookBean.getDocumentperiodical().setCategory_name(TextUtils.isEmpty(bookBean.getDtitle()) ? "" : bookBean.getDtitle());
          }
          getMvpView().getMyBookListSuccess(bookBeans);
        }
      }

      @Override
      public void onError(Throwable e) {
        super.onError(e);
        if (isAttachView())
          getMvpView().getMyBookListFailed();
      }
    }));
  }

  @Override
  public void delMyBook(List<MyBookBean> myBookBeans) {
    if (!isAttachView()) return;
    if (myBookBeans.size() <= 0) return;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < myBookBeans.size(); i++)
    {
      sb.append(myBookBeans.get(i).getPeriodical_id());
      if (i < myBookBeans.size() - 1)
      {
        sb.append(",");
      }
    }
    getMvpView().showLoading();
    getCompositeDisposable().add(getDbManager().delBook(getCurrentUser().getUserId(),sb.toString()).compose(JvtdRxSchedulers.handleObservableResult())
    .subscribeWith(new JvtdObserverSubscriber<EmptyBean>(getMvpView()){
      @Override
      public void onNext(EmptyBean emptyBean) {
        super.onNext(emptyBean);
        if (isAttachView())
          getMvpView().delMyBookSuccess();
      }
    }));
  }
}
